#!/usr/bin/env python

import json
import sys

import jinja2


def show_help():
    print("Usage:")
    print("    jsontmpl -f <TEMPLATE-FILE>   [-p <PARAM-fILE>]  [-o <OUTPUT-FILE>]")
    print("    jsontmpl -s <TEMPLATE-STRING> [-p <PARAM-fILE>]")
    return 0


# def render_file(infile, outfile, tmplfile):
#     text = infile.read()
#     template = jinja2.Template(text)
#     outfile.write(template.render(ARGS=json.load(tmplfile)))
#     return 0

def render_file(params_filepath: str, tmplat_filepath: str, output_filepath: str) -> int:
    tmplatfile = None
    outputfile = None
    paramsfile = None
    try:
        tmplatfile = open(tmplat_filepath, 'r')

        outputfile = sys.stdout
        if output_filepath != "":
            outputfile = open(output_filepath, 'w+')

        paramsfile = sys.stdin
        if params_filepath != "":
            paramsfile = open(params_filepath, 'r')

        template = jinja2.Template(tmplatfile.read())
        outputfile.write(template.render(ARGS=json.load(paramsfile)))
        return 0
    finally:
        if tmplat_filepath != "":
            tmplatfile.close()
        if output_filepath != "":
            outputfile.close()
        if params_filepath != "":
            paramsfile.close()


def render_string(params_filepath: str, tmplat_string: str):
    paramsfile = None
    try:
        outputfile = sys.stdout

        paramsfile = sys.stdin
        if params_filepath != "":
            paramsfile = open(params_filepath, 'r')

        template = jinja2.Template(tmplat_string)
        outputfile.write(template.render(ARGS=json.load(paramsfile)))
        return 0
    finally:
        if params_filepath != "":
            paramsfile.close()


def main(argv: [str]) -> int:
    if len(argv) < 2:
        print("Missing parameters, type -h for help", file=sys.stderr)
        return 1

    if argv[1] == '-h' or argv[1] == '--help':
        return show_help()

    params_filepath = ""
    output_filepath = ""
    tmplat_filepath = ""
    tmplat_string = ""
    rndlst_filename = ""

    i = 1
    while i < len(argv):
        if argv[i] == '-p':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-p'", file=sys.stderr)
                return 1
            params_filepath = argv[i + 1]
            i += 2
            continue
        if argv[i] == '-o':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-o'", file=sys.stderr)
                return 1
            output_filepath = argv[i + 1]
            i += 2
            continue

        if argv[i] == '-f':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-f'", file=sys.stderr)
                return 1
            tmplat_filepath = argv[i + 1]
            i += 2
            continue

        if argv[i] == '-s':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-s'", file=sys.stderr)
                return 1
            tmplat_string = argv[i + 1]
            i += 2
            continue

        #   不支持的参数
        print("Unsupported parameter {}".format(argv[i]), file=sys.stderr)
        return 1

    if tmplat_filepath != "":
        return render_file(params_filepath, tmplat_filepath, output_filepath)
    if tmplat_string != "":
        return render_string(params_filepath, tmplat_string)

    print("Expect -f or -s parameter", file=sys.stderr)
    return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv))
